package com.cp.exception;


import com.cp.response.Result;
import com.cp.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLDataException;
import java.sql.SQLException;

/**
 * @author : CP
 * @version: 1.0
 * @program : xinguan-parent
 * @description : 异常处理类
 * @date : 2020-12-01 12:42
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局异常处理,没有指定异常的类型,不管什么异常都是可以捕获的
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        //e.printStackTrace();
        log.error(e.getMessage());
        return Result.error();
    }

    /**
     * 处理算数异常类型
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e){
        //e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().code(ResultCode.ARITHMETIC_EXCEPTION.getCode())
                .message(ResultCode.ARITHMETIC_EXCEPTION.getMessage());
    }

    /**
     * 处理SQL数据异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLDataException.class)
    @ResponseBody
    public Result error(SQLDataException e){
        //e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().code(ResultCode.SQLDATA_EXCEPTION.getCode())
                .message(ResultCode.SQLDATA_EXCEPTION.getMessage());
    }

    /**
     * SQL语法异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public Result error(SQLException e){
        log.error(e.getMessage());
        return Result.error().code(ResultCode.SQL_EXCEPTION.getCode())
                .message(ResultCode.SQL_EXCEPTION.getMessage());
    }

    /**
     * 处理业务异常,我们自己定义的异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result error(BusinessException e){
        //e.printStackTrace();
        log.error(e.getErrMsg());
        return Result.error().code(e.getCode())
                .message(e.getErrMsg());
    }
}
